package com.jeeplus.test.jlnu.archivalInfo.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.AdmissionInfo;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.AllInfo;
import com.jeeplus.test.jlnu.admissionInfo.mapper.AdmissionInfoMapper;
import com.jeeplus.test.jlnu.archivalBatch.util.DateUtils;
import com.jeeplus.test.jlnu.archivalInfo.domain.entity.ArchParmerter;
import com.jeeplus.test.jlnu.archivalInfo.domain.vo.ArchivalInfoReqVo;
import com.jeeplus.test.jlnu.archivalInfo.service.ArchivalInfoService;
import com.jeeplus.test.jlnu.student.domain.result.Node;
import com.jeeplus.test.postgraduate.domain.vo.PostgraduateReqVo;
import com.jeeplus.test.tools.resp.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import oracle.jdbc.proxy.annotation.Post;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Api(tags = "档案信息")
@RestController
@Slf4j
@RequestMapping("/archivalInfo")
public class ArchivalInfoController {

    @Autowired
    private ArchivalInfoService archivalInfoService;

    @Autowired
    private AdmissionInfoMapper admissionInfoMapper;

    @ApiOperation("档案信息分页查询")
    @GetMapping("/page")
    public Page<ArchivalInfoReqVo> getArchivalInfoPage(ArchivalInfoReqVo archivalInfoReqVo, @RequestParam(defaultValue = "1") int pageNum,
                                                       @RequestParam(defaultValue = "10") int pageSize) {
        Page<ArchivalInfoReqVo> page = new Page<>(pageNum, pageSize);
        Page<ArchivalInfoReqVo> pageResult = archivalInfoService.getArchivalInfoPage(archivalInfoReqVo, page);
        return pageResult;
    }

    @ApiOperation("根据学号修改档案信息")
    @PostMapping("/updateArchival")
    public R updateArchival(@RequestBody List<ArchivalInfoReqVo> archivalInfoReqVo) {

        for (int i = 0; i < archivalInfoReqVo.size(); i++) {
            archivalInfoService.updateArchival(archivalInfoReqVo.get(i));

        }
        return R.suc();
    }

    @ApiOperation("档案信息新增")
    @PostMapping("/addArchival")
    public R addArchival(@RequestBody ArchivalInfoReqVo archivalInfoReqVos) {

        if (StringUtils.isEmpty(archivalInfoReqVos.getDateTime())) {
            String msg = "日期不能为空";
            return R.error("9999", msg);
        }
        if (StringUtils.isEmpty(archivalInfoReqVos.getMaterialId())) {
            String msg = "材料类别不能为空";
            return R.error("9999", msg);
        }
        String xh = archivalInfoReqVos.getStudentId();
        int count = admissionInfoMapper.checkStudentId(xh);
        if (StringUtils.isEmpty(xh)) {
            String msg = "姓名：(" + archivalInfoReqVos.getName() + ")学号为空请输入学号！";
            return R.error("9999", msg);
        }
        if (count < 1) {
            String msg = "姓名：（" + archivalInfoReqVos.getName() + "）学号不存在";
            return R.error("9999", msg);
        }
        archivalInfoReqVos.setStatus("1");
        archivalInfoReqVos.setArchivalStatus("1");
        archivalInfoReqVos.setDateTime(DateUtils.getCurrentDate());
        archivalInfoService.addArchival(archivalInfoReqVos);
        return R.suc();
    }

    @ApiOperation("主表信息树")
    @PostMapping("admissionTree")
    public String buildDirectoryTree(ArchivalInfoReqVo archivalInfoReqVo) throws JsonProcessingException {
        Map<String, Map<String, List<String>>> tree = new LinkedHashMap<>();
        // 3. 根据院校ID执行查询
        List<AdmissionInfo> admissionInfos = archivalInfoService.selectAllByOfficeId(archivalInfoReqVo);

        for (AdmissionInfo row : admissionInfos) {
            // 检查 row 是否为 null，防止对 null 进行方法调用
            if (row == null) {
                continue; // 如果 row 为 null，则跳过这次循环
            }

            // 安全地获取各个字段，防止空指针异常
            String academy = row.getAdmissionAcademy();
            String major = row.getAdmissionMajor();
            String time = row.getAdmissionTime() != null ? row.getAdmissionTime().toString() : null;

            // 如果任何一个字段为 null，则不处理该条记录
            if (academy != null && major != null && time != null) {
                tree.computeIfAbsent(academy, k -> new LinkedHashMap<>())
                        .computeIfAbsent(time, k -> new ArrayList<>())
                        .add(major);
                //tree.computeIfAbsent(major, k -> new ArrayList<>());
                // 保证去重
                Set<String> set = new HashSet<>(tree.get(academy).get(time));
                tree.get(academy).put(time, new ArrayList<>(set));
            }
        }

        // 假设convertToTargetFormat方法可以处理空数据并将数据转换为目标格式
        List<Node> formattedTree = convertToTargetFormat(tree);

        // 返回JSON字符串
        return new ObjectMapper().writeValueAsString(formattedTree);
    }

    private List<Node> convertToTargetFormat(Map<String, Map<String, List<String>>> data) {
        List<Node> result = new ArrayList<>();

        if (data == null || data.isEmpty()) {
            return result;
        }

        for (Map.Entry<String, Map<String, List<String>>> academyEntry : data.entrySet()) {
            String academyName = academyEntry.getKey();
            if (academyName == null || academyEntry.getValue() == null || academyEntry.getValue().isEmpty()) {
                continue;
            }

            Node academyNode = new Node(academyName);

            for (Map.Entry<String, List<String>> majorEntry : academyEntry.getValue().entrySet()) {
                String majorName = majorEntry.getKey();
                if (majorName == null || majorEntry.getValue() == null || majorEntry.getValue().isEmpty()) {
                    continue;
                }

                Node majorNode = new Node(majorName);

                for (String time : majorEntry.getValue()) {
                    if (time == null) {
                        continue;
                    }
                    Node timeNode = new Node(time);
                    majorNode.addChild(timeNode);
                }

                if (!majorNode.getChildren().isEmpty()) {
                    academyNode.addChild(majorNode);
                }
            }

            if (!academyNode.getChildren().isEmpty()) {
                result.add(academyNode);
            }
        }
        return result;
    }


    //批量移交
    @ApiOperation("批量移交")
    @PostMapping("/batchUpdateArchiva")
    public R batchUpdateArchiva(@RequestBody ArchivalInfoReqVo archivalInfoReqVo) {
        // 参数校验
        if (CollectionUtils.isEmpty(archivalInfoReqVo.getAdmissionInfoList())) {
            return R.error("9999", "请选择需要移交的数据");
        }
        archivalInfoService.batchUpdateArchiva(archivalInfoReqVo);
        return R.suc();
    }

}
